package com.xindaoapp.happypet.adapter;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.activity.PrivateLetterActivity;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.MessageCenterInfo;
import com.xindaoapp.happypet.fragments.SystemInformFragment;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.CircleImageView;

public class ReplyMessageCenterAdapter extends XinDaoBaseAdapter<MessageCenterInfo> {

    public enum MESSAGETYPE {
        /** 私信 */
        APP_PM("app_pm"),
        /** 回复 */
        POST("post"),
        /** 系统消息 */
        SYSTEM("system"),
        /** at 我 */
        AT("at");

        public String type;

        private MESSAGETYPE(String type) {
            this.type = type;
        }

    }

    /**
     * 私信类型
     * 
     * @author chenghao
     * 
     */
    enum APPPMTYPE {
        /** 我对谁说 */
        FA("fa"),
        /** 谁对我说 */
        SHOU("shou");
        String type;

        private APPPMTYPE(String type) {
            this.type = type;
        }
    }

    /**
     * 回复类型
     * 
     * @author chenghao
     * 
     */
    enum REPLYTYPE {
        /** 回复楼主 */
        POST("post"),
        /** 回复楼层 */
        QUOTE("quote");
        String type;

        private REPLYTYPE(String type) {
            this.type = type;
        }
    }

    public ReplyMessageCenterAdapter(Context context, List<MessageCenterInfo> iniData,
            int pageSize, int res, int loadingRes) {
        super(context, iniData, pageSize, res, loadingRes);
    }

    @Override
    public void nextPage(int start, int size,
            final ILoadNextPageData<MessageCenterInfo> iLoadNextPageData) {
        super.nextPage(start, size, iLoadNextPageData);
        HappyPetApplication.get().getMoccaApi()
                .getReplyMessageCenterInfos(start, size, new IRequest<List<MessageCenterInfo>>() {

                    @Override
                    public void request(List<MessageCenterInfo> t) {
                        iLoadNextPageData.loadNextPageData(t == null ? null : t);
                    }
                });
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent,
            final MessageCenterInfo value) {
        ViewHolder holder = (ViewHolder) convertView.getTag();
        if (holder == null) {
            holder = new ViewHolder();
            holder.icon = (CircleImageView) convertView.findViewById(R.id.user_icon);
            holder.title = (TextView) convertView.findViewById(R.id.title);
            holder.time = (TextView) convertView.findViewById(R.id.time);
            holder.content = (TextView) convertView.findViewById(R.id.content);
            holder.count = (TextView) convertView.findViewById(R.id.count);
            holder.replyContent = (TextView) convertView.findViewById(R.id.reply_content);
            holder.isNew = (ImageView) convertView.findViewById(R.id.red_point);
            holder.privateMessageLogo = convertView.findViewById(R.id.private_message_logo);
            convertView.setTag(holder);
        }
        ImageLoader.getInstance().displayImage(value.userface, holder.icon);
        if (value.type.equals(MESSAGETYPE.POST.type)) {
            holder.title.setText(value.author);
            holder.replyContent.setVisibility(View.VISIBLE);
            if (value.from_idtype.equals(REPLYTYPE.POST.type)) {
                if (value.subject.equals("")) {
                    holder.replyContent.setVisibility(View.GONE);
                } else {
                    holder.replyContent.setText(CommonUtil.convetToHtml(
                            CommonUtil.parseEmoji(String.format("回复我的主题：%s", value.subject)),
                            mContext));
                }

            } else if (value.from_idtype.equals(REPLYTYPE.QUOTE.type)) {

                if (value.mymessage.equals("")) {
                    holder.replyContent.setVisibility(View.GONE);
                } else {
                    holder.replyContent.setText(CommonUtil.convetToHtml(
                            CommonUtil.parseEmoji(String.format("回复我的评论：%s", value.mymessage)),
                            mContext));
                }


            } else {
                // TODO

                if (value.subject.equals("")) {
                    holder.replyContent.setVisibility(View.GONE);
                } else {
                    holder.replyContent.setText(CommonUtil.convetToHtml(
                            CommonUtil.parseEmoji(String.format("%s", value.subject)), mContext));
                }

            }

            holder.content.setText(CommonUtil.convetToHtml(CommonUtil.parseEmoji(value.message),
                    mContext));
            holder.count.setVisibility(View.VISIBLE);
            holder.privateMessageLogo.setVisibility(View.GONE);
        }

        if (value.isnew == 1) {
            holder.count.setVisibility(View.VISIBLE);
            holder.isNew.setVisibility(View.VISIBLE);
            holder.count.setText(String.valueOf(value.from_num > 99 ? "99+" : value.from_num));
        } else {
            holder.count.setVisibility(View.GONE);
            holder.isNew.setVisibility(View.GONE);
        }

        holder.time.setText(CommonUtil.formatTime(value.addtime));

        // final ViewHolder tempHolder = holder;

        // convertView.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // handleOnClick(value, tempHolder);
        // }
        // });

        // if (!value.type.equals(MESSAGETYPE.SYSTEM.type)) {
        // convertView.setOnLongClickListener(new OnLongClickListener() {
        //
        // @Override
        // public boolean onLongClick(View v) {
        // delete(value);
        // return false;
        // }
        // });
        // }

        return convertView;
    }

    private void handleOnClick(MessageCenterInfo info, ViewHolder holder) {
        if (info.type.equals(MESSAGETYPE.APP_PM.type)) {
            Intent i = new Intent(mContext, PrivateLetterActivity.class);
            i.putExtra(Constants.KEY_TOUID, info.authorid);
            i.putExtra(Constants.KEY_USERNAME, info.author);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(i);
        } else if (info.type.equals(MESSAGETYPE.POST.type)) {
            Intent i = new Intent(mContext, PostDetailActivity.class);
            i.putExtra(Constants.KEY_POST_TID, info.tid);
            i.putExtra("pageNum", info.curpage);
            i.putExtra("floor", info.curposition);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(i);
        } else if (info.type.equals(MESSAGETYPE.SYSTEM.type)) {
            Intent intent = new Intent(mContext, MainActivity.class);
            intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                    SystemInformFragment.class.getCanonicalName());
            Bundle bundle = new Bundle();
            intent.putExtra(Constants.KEY_BUNDLE, bundle);
            mContext.startActivity(intent);
        }
        if (info.isnew == 1) {
            info.isnew = 0;
            holder.isNew.setVisibility(View.GONE);
            HappyPetApplication.get().getMoccaApi().noticeClick(info.id, new IRequest<Boolean>() {

                @Override
                public void request(Boolean t) {
                    if (t) {
                        Constants.NoticeLabel.sHasNewMessageNotice = true;
                    } else {
                        Constants.NoticeLabel.sHasNewMessageNotice = false;
                    }
                    Intent notice = new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                    mContext.sendBroadcast(notice);
                }
            });
        }
    }

    public class ViewHolder {
        public CircleImageView icon;
        public TextView title;
        public TextView content;
        public TextView time;
        public ImageView isNew;
        public TextView count;
        public TextView replyContent;
        public View privateMessageLogo;
    }

    private void delete(final MessageCenterInfo info) {
        AlertDialog dialog =
                new AlertDialog.Builder(mContext).setTitle("提醒").setMessage("确认删除？")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                HappyPetApplication
                                        .get()
                                        .getMoccaApi()
                                        .deleteNoticeMessage(info.id,
                                                info.type.equals(MESSAGETYPE.SYSTEM.type),
                                                new IRequest<Boolean>() {

                                                    @Override
                                                    public void request(Boolean t) {
                                                        if (t) {
                                                            getResult().remove(info);
                                                            notifyDataSetChanged();
                                                            mContext.sendBroadcast(new Intent(
                                                                    Constants.ACTION_RECEIVED_NOTICE));
                                                            Toast.makeText(mContext, "删除成功！",
                                                                    Toast.LENGTH_SHORT).show();
                                                        } else {
                                                            Toast.makeText(mContext, "删除失败！",
                                                                    Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                });
                            }
                        }).setPositiveButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        }).create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }
}
